package com.tingyun.sign.companyUser.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.tingyun.sign.activity.service.ActivityService;
import com.tingyun.sign.companyUser.service.CompanyUserService;
import com.tingyun.sign.core.entity.ScActivityBean;
import com.tingyun.sign.core.entity.ScUCompanyUserBean;
import com.tingyun.sign.core.entity.ScUManagerBean;
import com.tingyun.sign.utils.BaseController;
import com.tingyun.sign.utils.DateUtils;
import com.tingyun.sign.utils.MyAssert;
import com.tingyun.sign.utils.Page;
import com.yhd.export.util.ExcelUtils;

@Controller
@RequestMapping("companyUser")
public class CompanyUserController extends BaseController {

	private static Logger log = LoggerFactory.getLogger(CompanyUserController.class);
	
	@Autowired
	private CompanyUserService companyUserService;
	
	@Autowired
	private ActivityService activityService;
	
	/**
	 * 检查用户登录 	0:用户名不存在，1：密码错误，2：校验通过
	 */
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> upload(@RequestParam(value = "file", required = true) MultipartFile file, HttpSession session, ScUCompanyUserBean bean) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			//校验文件
			if(file == null) {
				map.put("info", "上传的文件为空");
			}else {
				Workbook workbook=null;
				//判断文件类型
	            if (file.getOriginalFilename().endsWith("xlsx")) {
	                workbook = new XSSFWorkbook(file.getInputStream());
	            } else if (file.getOriginalFilename().endsWith("xls")) {
	                workbook = new HSSFWorkbook(file.getInputStream());
	            }else {
	            	MyAssert.isTrue(false,"文件类型错误，请上传Excel文档");
	            }
            	MyAssert.notNull(bean.getActivityId(),"请选择活动");
	            //解析excel
				List<ScUCompanyUserBean> list = ExcelUtils.parseExcelToList(workbook, ScUCompanyUserBean.class, "upload_user");
				if(list!=null) {
					ScUManagerBean manager = getSessionUser(session);
					for(ScUCompanyUserBean obj : list) {
						obj.setActivityId(bean.getActivityId());
						obj.setCtime(new Date());
						obj.setMtime(new Date());
						obj.setCuser(manager.getId());
						obj.setMuser(manager.getId());
						obj.setStatus(0);
					}
				}
				//插入数据库
				Integer result = companyUserService.addUsers(list);
				map.put("result", result);
			}
		} catch (Exception e) {
			log.error("客户信息文件解析失败", e.getMessage());
			map.put("info", e.getMessage());
		}
		return map;
	}

	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> add(HttpSession session, ScUCompanyUserBean bean) {
		Map<String, Object> map = new HashMap<String, Object>();
		ScUManagerBean manager = getSessionUser(session);
		bean.setCuser(manager.getId());
		bean.setMuser(manager.getId());
		Integer result = null;
		try {
			result = companyUserService.addUser(bean);
		} catch (Exception e) {
			map.put("info", e.getMessage());
		}
		map.put("result", result);
		return map;
	}
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> edit(HttpSession session, ScUCompanyUserBean bean) {
		Map<String, Object> map = new HashMap<String, Object>();
		ScUManagerBean manager = getSessionUser(session);
		bean.setMuser(manager.getId());
		Integer result = null;
		try {
			result = companyUserService.updateUser(bean);
		} catch (Exception e) {
			map.put("info", e.getMessage());
		}
		map.put("result", result);
		return map;
	}
	@RequestMapping(value = "deleteUser", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteUser(HttpSession session, ScUCompanyUserBean bean) {
		Map<String, Object> map = new HashMap<String, Object>();
		ScUManagerBean manager = getSessionUser(session);
		bean.setMuser(manager.getId());
		Integer result = null;
		try {
			result = companyUserService.deleteUser(bean);
		} catch (Exception e) {
			map.put("info", e.getMessage());
		}
		map.put("result", result);
		return map;
	}
	
	/**
	 * 客户签到
	 * @param session
	 * @param bean
	 * @return
	 */
	@RequestMapping(value = "signIn")
	@ResponseBody
	public Map<String, Object> signIn(HttpSession session, ScUCompanyUserBean bean) {
		Map<String, Object> map = new HashMap<String, Object>();
		ScUManagerBean manager = getSessionUser(session);
		bean.setMuser(manager.getId());
		Integer result = null;
		try {
			result = companyUserService.signIn(bean);
		} catch (Exception e) {
			map.put("info", e.getMessage());
		}
		map.put("result", result);
		return map;
	}

	/**
	 * 活动列表
	 */
	@RequestMapping(value = "list")
	public ModelAndView list(HttpSession session, ScUCompanyUserBean bean) {
		bean.setStartTimeStr(DateUtils.converToStringDate(DateUtils.addDay(new Date(), -30), "yyyy-MM-dd"));
		bean.setEndTimeStr(DateUtils.converToStringDate(new Date(),"yyyy-MM-dd"));
		ModelAndView mv = new ModelAndView();
		List<ScActivityBean> acs = activityService.findAllActivities(getSessionUser(session).getType());
		mv.addObject("obj",bean);
		mv.addObject("acs",acs);
		mv.setViewName("companyUser/list");
		return mv;
	}
	
	@RequestMapping(value = "findPage")
	@ResponseBody
	public Map<String, Object> findCompanyUsers(ScUCompanyUserBean bean) {
		Map<String, Object> map = new HashMap<String, Object>();
		Page<ScUCompanyUserBean> page = companyUserService.findUserPage(bean);
		map.put("total", page.getTotalCount());
		map.put("result", page.getResultList());
		map.put("rows", page.getResultList());
		return map;
	}
	
}
